import {
    printImage,
    sendDataToDevice,
    overwriteImageData,
    printQR,
    printCommand,
} from '../../wx-weapp-tool/bluetoolth';

import GBK from '../../wx-weapp-tool/libs/gbk.min';

import getBluetoothPageConfig from '../../wx-weapp-tool/bluetoothConnectionTemplate/index';
const bluetoothConfig = getBluetoothPageConfig();
const constant = require("../../util/constant.js");
const util = require('../../util/util.js');
const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    ColorList: app.globalData.ColorList,
    ...bluetoothConfig.data,
        // 打印机纸张宽度，我用的打印几的纸张最大宽度是384，可以修改其他的
        paperWidth: 284,
        canvasWidth: 1,
        canvasHeight: 1,
        img: '',
        threshold: [200],
        percentage: 0,
        printing: false,
        corpname:'',
        corpno:'',
        corpcity:'',
        corpaddress:'',
        corplink:'',
        corpbank:'',
        printing: false,
        bankno:'',
        message: `            正阳县城市综合执法局
                                当场处罚决定书
                        郑城综当罚决字〔2022〕第2201012号 
        当事人姓名：获取当事人姓名
        年龄：获取当事人年龄
        你（单位）于___年___月___日___时___分在___________________因____________________________的行为，违反了__________________________________的规定，有证据___________________
        现责令你（单位）于_______年______月______日    _______时前自行__________________________                    
        现依据___________________________的规定、本局决定对你（单位）处以下行政处罚：                    
        警告；
        罚款人民币伍拾元整。￥:【50元】 缴纳罚款方式：
        当场收缴。（依据《中华人民共和国行政处罚法》第四十七条、第四十八条的规定）
        自收到本决定书之日起15日内将）罚款交至____银行（账  号：                  )。逾期未缴纳罚款的，可以每日按罚款数额的3%加处罚款。
        本局执法人员当场向你（单位）告知了违法事实、依据和依法享有的权利。陈述申辩情况：                                                          
        我于___年___月___日收到本处罚决定书、执法人员在处罚前已向我告知了权利，并听取了我的陈述和申辩。
        送达方式：___________________________________
        当事人签名：
        年     月      日`,
        checked: true,
        ajid:'',
        carnumber:'',
        zbrid:'',
        zbrbh:'',
        zbrname:'',
        zxbm:'',
        mycolor:'',
        mytype:'',
        wttimg:'',
        afaddr:'',
        afsj:'',
    deviceId:'',
    penaltytype:0,
    id:0
  },
  onHide() {
    bluetoothConfig.onHide.call(this);
    },
  onLoad: function (option) { 
    bluetoothConfig.onLoad.call(this, option);
    var mycorpname=wx.getStorageSync('cname');
    var mycorpno=wx.getStorageSync('cno');
    var mycorpcity=wx.getStorageSync('ccity');
    
    this.setData({
        corpname:mycorpname,
        corpno:mycorpno,
        corpcity:mycorpcity,
    })
    var mycorpaddress=wx.getStorageSync('caddr');
    var mycorplink=wx.getStorageSync('clink');
    var mycorpbank=wx.getStorageSync('cbank');
    var mybankno=wx.getStorageSync('bankno');
    
      var aid=option.aid;
      //console.log(aid);
      var myview="";
      var aywfl='';
      var aycfyj='';
      if(aid>0)
      {
       
        var that=this;
        wx.request({
            url: constant.host+'/appserv/getaycar.ashx',
            data: {
              aid:aid,
              k: constant.wkey
            },
            success: function (data) {
            
              var dat = data.data;
              if(dat.length>0)
              {
 
                  var mydata=dat[0];
               //console.log(mydata)
                let carno=mydata.CarNumber;
                let carcolor=mydata.CarColor;
                let cartype=mydata.CarType;
                let afaddr=mydata.GetAddr;
                let wftime=util.formatTimeToC(mydata.GetTime)
                let wfdate=util.formatDateToC(mydata.GetTime);
                let penaltytype = mydata.PenaltyType;
                var str='';
                if(penaltytype==1){
                  str='该机动车在上述时间、地点停放，违反了《中华人民共和国道路交通安全法》第五十六条、《中华人民共和国道路交通安全法实施条例》第六十三条,机动车违反规定停放，请于5日内持本告知单，到正阳县城市综合执法局接受处理。';
                }else{
                  str='该非机动车在上述时间，未按规定停放，违反了《中华人民共和国道路交通安全法》第五十九条的规定，根据《中华人民共和国道路交通安全法》第八十九条和《河南省道路交通安全条例》第五十一条第一款之规定，处以罚款￥20元整。请于5日内持本告知单，到正阳县城市综合执法局接受处理。';
                }
                myview=`            正阳县城市综合执法局
               违法停车告知单

编号：411791-000`+aid+`
车辆号牌：`+carno+`
机动车类型：`+cartype+`
车身颜色：`+carcolor+`
违法停车时间：`+wftime+`
违法停车地点：`+afaddr+`
违法行为：`+str+`            
(地址：正阳县南环路西段正阳公园南门西100米正阳县城市综合执法局车辆违章处置中心)
    告知人：`+mydata.CZBR+`

              正阳县城市综合执法局（签章）
                           `+wfdate+`  `;
//console.log(myview);
                that.setData({
                    ajid:aid,
                    carnumber:carno,
                    mycolor:carcolor,
                    mytype:cartype,
                    wttimg:wftime,
                    afaddr:afaddr,
                    zbrname:mydata.CZBR,
                      afsj:wfdate,
                      penaltytype:penaltytype,
                      message:myview
                 })
                  //console.log(mycorpname);
                  

                 
      
                      }
                      
                    }
                  });
                  
              }
              
              const ctx = wx.createCanvasContext('secondCanvas');
              let tempFilePath='https://zyzfj.114jcw.com/img/zyzfjz.png'
              wx.getImageInfo({
                  src: tempFilePath,
                  success: (res) => {
                      
                  var path = res.path;
                  //console.log("图片新路径")
                  //console.log(path);
                      // 打印宽度须是8的整数倍，这里处理掉多余的，使得宽度合适，不然有可能乱码
                      const mw = this.data.paperWidth % 8;
                      const w = mw === 0 ? this.data.paperWidth : this.data.paperWidth - mw;
                      //const mk=284;
                      //const mw = mk % 8;
                      //const w = mw === 0 ? mk : mk - mw;
                      // 等比算出图片的高度
                      const h = Math.floor((res.height * w) / res.width);
                      
                      // 设置canvas宽高
                      this.setData({
                          img: path,
                          canvasHeight: h,
                          canvasWidth: w,
                          //canvasWidth: 500,
        
                      });
                      // 在canvas 画一张图片
                      
                      ctx.fillStyle = 'rgba(255,255,255,1)';
                      //ctx.fillStyle = 'rgba(0,0,0,0)';
                      ctx.clearRect(0, 0, w, h);
                      ctx.fillRect(0, 0, w, h);
                      ctx.drawImage(path, 0, 0, w, h);
                      ctx.draw(false, () => {
                          wx.hideLoading();
                      });
                  /*
                      setTimeout(() => {
                          this.printImage()
                          },200)*/
                  },
                  fail: (res) => {
                      console.log('get info fail', res);
                      wx.hideLoading();
                  },
              }); 
  },
  pageBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  printImage() {
    if (!this.data.deviceId) {
        wx.showToast({
            title: '未连接任何蓝牙设备',
            icon: 'none',
        });
        return;
    }
    if (this.lock === true) {
        console.log('lock');
        return;
    }
    this.lock = true;
    // 选择一张图片
    const { img } = this.data;
    //console.log("要打印的图片")
    //console.log(img);
    //console.log(this.data);
    if (!img) {
        wx.showToast({
            title: '未获取图片',
            icon: 'none',
        });
        this.lock = false;
        return;
    }
    const { canvasWidth, canvasHeight, deviceId, threshold } = this.data;
    //console.log('threshold', threshold);
    //获取画布里的图片数据
    wx.canvasGetImageData({
        canvasId: 'secondCanvas',
        x: 0,
        y: 0,
        width: canvasWidth,
        height: canvasHeight,
        success: (res) => {
            const pix = res.data;
            //console.log("pix")
            //console.log(pix);
            const opt = {
                deviceId,
                ...this.character,
                onProgress: (percentage) => {
                    console.log('percentage', percentage);
                    this.setData({
                        percentage,
                    });
                },
                printAlign:"center",
                lasterSuccess: () => {
                    console.log('laster success');
                    this.setData({
                        printing: false,
                        percentage: 0,
                    });
                    wx.showModal({
                        title: '提示',
                        content: '打印完成，请检查打印的内容是否正常',
                        showCancel: false,
                        confirmText: '好的',
                    });
                },
            };
            this.setData({
                printing: true,
            });
            //打印图片
            printImage(
                opt,
                // 将图片数据转成位图数据
                overwriteImageData({
                    threshold: threshold[0],
                    imageData: pix,
                    width: canvasWidth,
                    height: canvasHeight,
                }),
            );
        },
        complete: () => {
            this.lock = false;
        },
    });
},
  onUnload() {
    bluetoothConfig.onUnload.call(this);
    },
    onPullDownRefresh() {
        bluetoothConfig.onPullDownRefresh.call(this);
    },
    ...bluetoothConfig.methods,
  doprint(e){
    
       /*
      var that=this;
    wx.openBluetoothAdapter({//初始化蓝牙
        success: function (res) {
          wx.getBluetoothAdapterState({//获取本机蓝牙适配器状态。
            success: function (res) {
              if (res.available) {//蓝牙适配器是否可用
               //下一步操作
               wx.startBluetoothDevicesDiscovery({//搜索附近的蓝牙设备
                services: [],//筛选过滤搜索的蓝牙设备
                success(res) {
                  setTimeout(() => {
                    wx.getBluetoothDevices({//获取蓝牙列表
                      services: [],
                      success: function (res) {
                        //callback(res);//返回蓝牙列表
                       
                        var dat=res.devices;
                        //console.log(res);
                        //console.log(dat);
                        var dvid="";
                        for(var i=0;i<dat.length;i++)
                        {
                            //console.log(dat[i].name);
                            if(dat[i].name=="H98")
                            {
                                dvid=dat[i].deviceId;
                            }
                        }
                        console.log(dvid);
                        that.setData({
                            deviceId:dvid
                        })
                      },
                      fail(res) {
                        wx.showModal({
                          title: '提示',
                          content: '获取蓝牙设备列表失败',
                        })
                      }
                    })
                  }, 2000)
                  //关闭搜索
                  wx.stopBluetoothDevicesDiscovery({
                    success: function (res) {}
                  })
                }
              })         
              } else {
                wx.showModal({
                  title: '提示',
                  content: '本机蓝牙不可用',
                })
              }
            }
          })
        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: '蓝牙初始化失败，请打开蓝牙',
          })
        }
      }) */
      //console.log('获取的设备信息'+this.data.deviceId);
      
      if (!this.data.deviceId) {
        wx.showToast({
            title: '未连接任何蓝牙设备',
            icon: 'none',
        });
        return;
        
    }
    //console.log("did:"+this.data.devices[0].devId);
    //const opt = { deviceId: this.data.devices[0].devId, ...this.character };
    const opt = { deviceId: this.data.devices[0].devId, ...this.character };
    //console.log(...GBK.encode(this.data.message));
    sendDataToDevice({
        ...opt,
        value: new Uint8Array([...printCommand.clear, ...GBK.encode(this.data.message), ...printCommand.enter])
            .buffer,

        lasterSuccess: () => {
          this.printImage();
            //console.log('打印')
            // 用指令打印二维码
            //if (this.data.checked) {
                /*
                printQR({
                    ...opt,
                    value: new Uint8Array(GBK.encode('https://www.baidu.com/')).buffer,
                });
                */
            //}
        },
    });     
  }
});
